package com.example.demo.controller;

import com.example.demo.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Admin
 * Date: 2023-03-12
 * Time: 16:41
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServer userServer;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/add")
    public int add(String username,String password) {
        //非空效验
        if(!StringUtils.hasLength(password) || !StringUtils.hasLength(username)) {
            return 0;
        }
         //得到并开启事务
        TransactionStatus transactionStatus =  dataSourceTransactionManager
                .getTransaction(transactionDefinition);
        //插入数据
         int result =  userServer.add(username,password,null);
        System.out.println("插入结果:" + result);

        //事务回滚  上方插入数据成功,但是事务进行回滚了,如果数据库没有数据表示数据回滚成功.
        dataSourceTransactionManager.rollback(transactionStatus);
        //事务提交   如果不需要回滚,就可以用这个提交数据
        dataSourceTransactionManager.commit(transactionStatus);

        return result;
    }

    @RequestMapping("/add2")
    @Transactional
    public int add2(String username,String password) {
        //非空效验
        if(!StringUtils.hasLength(password) || !StringUtils.hasLength(username)) {
            return 0;
        }


        //插入数据
        int result =  userServer.add(username,password,null);
        System.out.println("插入结果:" + result);

        try {
            int sum = 10 / 0;
        } catch (Exception e) {
            //手动抛出异常
            //throw e;

            //手动回滚事务
            System.out.println(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }
}
